package Zim::TextBuffer;

use strict;
use Carp;

our $VERSION = '0.18';

=head1 NAME

Zim::Buffer - Scalar with file like API

=head1 DESCRIPTION

This object implements part of the API of Zim::File
but keeps all data in memory. Used as a mock object
for file-based APIs within Zim.

=head1 METHODS

=over 4

=item C<new(\$STRING)>

Simple constructor, takes a scalar ref as argument.

=item C<read()>

Returns contents.

=item C<write(TEXT)>

Sets contents.

=item C<append(TEXT)>

Appends contents.

=item C<open(MODE)>

Returns a file handle.

=item C<exists()>

True if content defined.

=item C<remove()>

Delete content.

=cut

sub new {
	my ($class, $ref) = @_;
	$ref ||= \"";
	croak "usage: new(\\\$STRING)" unless ref($ref) eq 'SCALAR';
	bless \$ref, $class;
}

sub read {
	my $text = $${$_[0]};
	return wantarray ? (map "$_\n", split /\n/, $text) : $text;
}

sub write { $${$_[0]} = join '', @_[1 .. $#_] }

sub append { $${$_[0]} = join '', $${$_[0]}, @_[1 .. $#_] }

sub open {
	my ($self, $mode) = @_;
	my $fh;
	$mode = ($mode eq 'w') ? '>' : ($mode eq 'a') ? '>>' : '<' ;
	open $fh, $mode, $$self or die "BUG $!";
	return $fh;
}

sub exists { defined $${$_[0]} }

sub remove { $${$_[0]} = undef }


1;

__END__

=back

=head1 AUTHOR

Jaap Karssenberg (Pardus) E<lt>pardus@cpan.orgE<gt>

Copyright (c) 2007 Jaap G Karssenberg. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=head1 SEE ALSO

=cut

